package models

import (
	"errors"
	"fmt"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
	"hc_server/pkg/setting"
	"hc_server/routers/response/deviceResponse"
)

// DeviceModel 设备型号
type DeviceModel struct {
	Model
	Icon         string `json:"icon"`
	DeviceNo     string `json:"device_no" gorm:"comment:'设备型号'"`
	DeviceType   string `json:"device_type" gorm:"comment:'设备型号详细'"`
	DeviceTypeId int    `json:"device_type_id" gorm:"comment:'设备名称 deviceType主键id'"`
}

// ExistDeviceModelById 通过id判断是否存在
func ExistDeviceModelById(id int) (bool, error) {
	var model DeviceModel
	err := db.Model(&model).Where("id = ?", id).First(&model).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logrus.WithError(err).Errorf("获取设备类型失败 model: %v err:%v", model, err)
		return false, fmt.Errorf("获取设备类型失败")
	}

	return model.ID > 0, nil
}

// DeviceModelInfoAdd 添加设备类型
func DeviceModelInfoAdd(model DeviceModel) error {
	err := db.Create(&model).Error
	if err != nil {
		logrus.WithError(err).Errorf("添加设备失败 err:%v,model:%v", err, model)
		return errors.New("添加设备失败")
	}
	return nil
}

// DeviceModelInfoList 设备类型列表
func DeviceModelInfoList(agentId, pageNum, pageSize int) (map[string]interface{}, error) {
	var (
		result = make([]*deviceResponse.GetDeviceModelInfoListResponse, 0)
		count  int64
	)
	path := setting.GetConfig().App.RuntimeRootPath + "device/"
	selectd := fmt.Sprintf("devices.device_model_id AS device_model_id,CONCAT('%s',device_models.icon) AS icon,"+
		"COUNT(DISTINCT binding.id) AS binding_count,COUNT(DISTINCT unbinding.id) AS unbinding_count,"+
		"COUNT(DISTINCT allocate.id) AS allocate_count,COUNT(DISTINCT recall.id) AS recall_count", path)
	err := db.Select(selectd).
		Model(&Device{}).
		Joins("LEFT JOIN devices AS binding ON binding.binding_status = 1 AND binding.device_model_id = devices.device_model_id").                                                                        //获取绑定数量
		Joins("LEFT JOIN devices AS unbinding ON unbinding.binding_status = 0 AND unbinding.device_model_id = devices.device_model_id").                                                                  //获取未绑定数量
		Joins("LEFT JOIN devices AS allocate ON allocate.binding_status = 0 AND allocate.activate_status = 0 AND allocate.device_model_id = devices.device_model_id AND allocate.agent_id = ?", agentId). //获取可划拨设备数量
		Joins("LEFT JOIN agent_relations ON FIND_IN_SET( devices.agent_id, agent_relations.relation )").
		Joins("LEFT JOIN devices AS recall ON recall.binding_status = 0 AND recall.agent_id = agent_relations.agent_id AND recall.activate_status = 0 AND recall.device_model_id = devices.device_model_id").
		Joins("JOIN device_models ON device_models.id = devices.device_model_id").
		Where("devices.agent_id = ?", agentId).
		Group("devices.device_model_id").
		Limit(pageSize).
		Offset((pageNum - 1) * pageSize).
		Order("device_models.created_at DESC").
		Scan(&result).Error

	if err != nil {
		logrus.WithError(err).Errorf("添加设备失败 err:%v,agentId:%v", err, agentId)
		return nil, errors.New("添加设备失败")
	}

	db.Model(&DeviceModel{}).Count(&count)

	return map[string]interface{}{
		"count": count,
		"list":  result,
	}, nil
}
